package kr.hkit.androidcomplete02.XMLparser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import kr.hkit.androidcomplete02.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class Json_parserAcitivity extends Activity {
	
	private ListView list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		
		new ParsingXML().execute("order.json");
		
	}
	
	private class ParsingXML extends AsyncTask<String, Void, ArrayList<Item>> {
		private ProgressDialog progressDlg;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDlg = ProgressDialog.show(Json_parserAcitivity.this, "Wait", "xml parsing...");
		}
		
		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			super.onPostExecute(result);
			MyAdapter adapter = new MyAdapter(Json_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
			
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine())!=null){
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		// Json parser는 이부분
		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arItem = new ArrayList<Item>();
			Item itemClass;

			try {
				JSONArray ja = new JSONArray(xml);
				for (int i = 0; i < ja.length(); i++) {
					JSONObject itemObj = ja.getJSONObject(i);
					itemClass = new Item();
					
					// order.jason파일의 속성명과같아야함
					itemClass.setItemName(itemObj.getString("Product")); 
					itemClass.setMakerName(itemObj.getString("Maker"));
					itemClass.setItemPrice(itemObj.getInt("Price"));
					arItem.add(itemClass);
				}
			} catch (JSONException e) {
			}

			return arItem;
		}
	}
}
